package com.onefive.android.adapter;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.onefive.android.R;
import com.onefive.android.db.YtubeColumns;
import com.onefive.android.db.YtubeQuery;
import com.onefive.android.model.YouTubeObject;
import com.onefive.android.service.UpdateService;
import com.onefive.android.utils.Config;
import com.onefive.android.utils.DetachableResultReceiver;
import com.onefive.android.utils.DetachableResultReceiver.Receiver;
import com.onefive.android.utils.NotifyingAsyncQueryHandler;

public final class TestFragment extends Fragment implements OnClickListener, OnItemClickListener, Receiver, OnScrollListener, NotifyingAsyncQueryHandler.AsyncQueryListener {
	private static final String KEY_CONTENT = "TestFragment:Content";
	private ListView listView;
	private TextView loading;
	private static final String RU = "AdamThomasMoran";
	private static final String US = "plus100500eng";
	private DetachableResultReceiver receiver;
	// private static final String SHOW_PROGRESS = "show_progress";
	private YtubeAdapter adapter;
	private Button button;
	private Cursor mCursor;
	private int limit;
	private boolean visibility = true;
	private int token;
	private int total;
	private NotifyingAsyncQueryHandler mHandler;

	public static TestFragment newInstance(String content) {
		TestFragment fragment = new TestFragment();
		fragment.mCursor = null;
		if (content.equals(TestFragmentAdapter.CONTENT[0])) {
			fragment.mContent = RU;
			fragment.token = 0;
		} else if (content.equals(TestFragmentAdapter.CONTENT[1])) {
			fragment.mContent = US;
			fragment.token = 1;
		}
		fragment.limit = Config.step_limit;
		fragment.total = Integer.MAX_VALUE;

		return fragment;
	}

	private String mContent = "???";

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		if ((savedInstanceState != null) && savedInstanceState.containsKey(KEY_CONTENT)) {
			mContent = savedInstanceState.getString(KEY_CONTENT);
		}
		mHandler = new NotifyingAsyncQueryHandler(getActivity().getContentResolver(), this);
		View view = inflater.inflate(R.layout.main, null);
		listView = (ListView) view.findViewById(R.id.list);
		loading = (TextView) view.findViewById(R.id.loading);
		button = (Button) view.findViewById(R.id.show_more);
		button.setVisibility(View.GONE);
		button.setOnClickListener(this);
		listView.setOnItemClickListener(this);
		listView.setOnScrollListener(this);
		receiver = new DetachableResultReceiver(new Handler());
		receiver.setReceiver(this);
		updateList(1, 2 * Config.step_limit);
		mHandler.cancelOperation(token);
		mHandler.startQuery(token, null, YouTubeObject.CONTENT_URI, YtubeQuery.PROJECTION, YtubeColumns.TYPE.getName() + "=?", new String[] { mContent }, YouTubeObject.DATE_SORT + " limit "
				+ limit);

		return view;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		limit = Config.step_limit;
		super.onDestroy();
	}

	@Override
	public void onResume() {
		if (mCursor != null) {
			mCursor.requery();
		}
		super.onResume();
		super.onResume();
	}

	private void updateList(int start, int count) {
		Intent upfateIntent = new Intent(Intent.ACTION_SYNC, null, getActivity(), UpdateService.class);
		upfateIntent.putExtra(UpdateService.EXTRA_STATUS_RECEIVER, receiver);
		upfateIntent.putExtra(UpdateService.EXTRA_REQUEST_CODE, Config.YTUBE);
		upfateIntent.putExtra(Config.TYPE, mContent);
		upfateIntent.putExtra(Config.START, start);
		upfateIntent.putExtra(Config.COUNT, count);
		getActivity().startService(upfateIntent);
	}

	@Override
	public void onQueryComplete(int token, Object cookie, Cursor cursor) {
		if (getActivity() == null) {
			return;
		}
		switch (token) {
		case 0:
			if (cursor != null) {
				if (mCursor != null) {
					getActivity().stopManagingCursor(mCursor);
					mCursor = null;
				}
				mCursor = cursor;
				getActivity().startManagingCursor(mCursor);
				if (adapter == null) {
					adapter = new YtubeAdapter(getActivity(), mCursor);
					listView.setAdapter(adapter);
				} else {
					adapter.changeCursor(cursor);
					adapter.notifyDataSetChanged();
				}
				if (mCursor.moveToFirst()) {
					total = mCursor.getInt(YtubeQuery.SIZE);

				}
				// Log.e("totalsssssssssss", "" + total);
				loading.setVisibility((listView.getCount() == 0) ? View.VISIBLE : View.GONE);

			}
			break;
		case 1:
			if (cursor != null) {
				if (mCursor != null) {
					getActivity().stopManagingCursor(mCursor);
					mCursor = null;
				}
				mCursor = cursor;
				getActivity().startManagingCursor(mCursor);
				if (adapter == null) {
					adapter = new YtubeAdapter(getActivity(), mCursor);
					listView.setAdapter(adapter);
				} else {
					adapter.changeCursor(mCursor);
					adapter.notifyDataSetChanged();
				}

				if (mCursor.moveToFirst()) {
					total = mCursor.getInt(YtubeQuery.SIZE);
				}

				// Log.e("3333", "" + adapter.getCount());
				loading.setVisibility((listView.getCount() == 0) ? View.VISIBLE : View.GONE);

			}
			break;
		default:
			break;
		}

	}

	@Override
	public void onReceiveResult(int resultCode, Bundle resultData) {
		switch (resultCode) {
		case UpdateService.STATUS_RUNNING:
			break;
		case UpdateService.STATUS_ERROR:
			break;
		case UpdateService.STATUS_FINISHED:

			if (mCursor != null && getActivity() != null) {
				getActivity().stopManagingCursor(mCursor);
				mCursor = null;
			}
			mHandler.cancelOperation(token);
			mHandler.startQuery(token, null, YouTubeObject.CONTENT_URI, YtubeQuery.PROJECTION, YtubeColumns.TYPE.getName() + "=?", new String[] { mContent }, YouTubeObject.DATE_SORT
					+ " limit " + limit);

		}
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {

	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
		button.setVisibility((visibility && totalItemCount - firstVisibleItem < 4) ? View.VISIBLE : View.GONE);
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putString(KEY_CONTENT, mContent);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.show_more:
//			Log.e("asdasdasdas", "" + total);
			button.setVisibility(View.GONE);
			limit += Config.step_limit;
			if (limit > total) {
				visibility = false;
			} else {
				updateList(limit, Config.step_limit);
			}

			// if (mCursor != null) {
			// mCursor.requery();
			// }
			if (mCursor != null && getActivity() != null) {
				getActivity().stopManagingCursor(mCursor);
				mCursor = null;
			}
			mHandler.cancelOperation(token);
			mHandler.startQuery(token, null, YouTubeObject.CONTENT_URI, YtubeQuery.PROJECTION, YtubeColumns.TYPE.getName() + "=?", new String[] { mContent }, YouTubeObject.DATE_SORT
					+ " limit " + limit);

		default:
			break;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
		YtubeAdapter adapter = (YtubeAdapter) adapterView.getAdapter();
		Cursor cursor = adapter.getCursor();
		if (cursor != null && cursor.moveToPosition(position)) {
			String idVideo = cursor.getString(YtubeQuery._ID);
			try {
				Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube://" + idVideo));
				startActivity(intent);
			} catch (Exception e) {
				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.setData(Uri.parse("market://search?q=pname:com.google.android.youtube"));
				try {
					startActivity(intent);
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
		}
	}

}
